package com.ikingtech.framework.sdk.job.embedded;

import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.enums.common.FrameworkAgentTypeEnum;
import com.ikingtech.framework.sdk.enums.job.JobTypeEnum;
import com.ikingtech.framework.sdk.job.model.JobDTO;
import com.ikingtech.framework.sdk.web.support.agent.FrameworkAgentProxy;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * @author tie yan
 */
@Slf4j
public class JobOps {

    private final JobDTO job = new JobDTO();

    /**
     * 仅执行一次的定时任务
     *
     * @return 定时任务操作
     */
    public static JobOps once() {
        JobOps operation = new JobOps();
        operation.job.setType(JobTypeEnum.ONCE);
        return operation;
    }

    /**
     * 周期性定时任务
     *
     * @return 定时任务操作
     */
    public static JobOps repeat() {
        JobOps operation = new JobOps();
        operation.job.setType(JobTypeEnum.REPEATEDLY);
        return operation;
    }

    public JobOps handler(String handler) {
        this.job.setExecutorHandler(handler);
        this.job.setName(handler);
        return this;
    }

    /**
     * 下一次执行时间
     * 创建仅执行一次的定时任务时指定
     *
     * @param nextTime 执行时间
     */
    public JobOps nextTime(LocalDateTime nextTime) {
        this.job.setNextTime(nextTime);
        return this;
    }

    /**
     * 定时任务执行时间的cron表达式
     * 创建周期性定时任务时指定
     *
     * @param cron cron表达式
     */
    public JobOps cron(String cron) {
        this.job.setCron(cron);
        return this;
    }

    /**
     * 定时任务执行时需要的参数
     *
     * @param param 参数
     */
    public JobOps param(String param) {
        this.job.setParam(param);
        return this;
    }

    /**
     * 启动定时任务
     *
     * @return 执行结果
     */
    public R<Object> start() {
        this.job.setExecutorClientId(JobExecutorBeanFactory.getClientId());
        return FrameworkAgentProxy.agent().execute(FrameworkAgentTypeEnum.JOB_START, this.job);
    }

    /**
     * 停止定时任务
     *
     * @return 执行结果
     */
    public static R<Object> stop(String id) {
        return FrameworkAgentProxy.agent().execute(FrameworkAgentTypeEnum.JOB_STOP, id);
    }
}
